<script setup lang="ts">
import type { FormInstance } from 'element-plus';
import { useAuthenticationStore } from 'my-vue-core/stores';
import { HelloWorld } from 'my-vue-ui-core/components';
import { reactive, ref } from 'vue';
import { useRoute } from 'vue-router';

import {
  AuthenticationService,
  RememberMeService,
  Token,
  TokenService,
} from 'my-web-core/auth';

import { User } from 'my-web-core/auth';
import { FormTextFieldValidator } from 'my-web-core/validators';

import router from '@/app-router';
import AuthService from '@/features/authentication/services/auth-service';

import 'my-vue-ui-core/style.css';

const route = useRoute();
const authenticationStore = useAuthenticationStore();
const ruleFormRef = ref<FormInstance>();

const ruleForm = reactive({
  username: authenticationStore.currentUsername,
  password: '',
  rememberMe: RememberMeService.rememberMe,
});

const rules = reactive({
  username: [
    {
      validator: (_rule: any, value: any, callback: any) => {
        const errorMessage = new FormTextFieldValidator({
          label: '用户名',
          value: value,
        }).validate();

        errorMessage ? callback(new Error(errorMessage)) : callback();
      },
      trigger: 'change',
    },
  ],
  password: [
    {
      validator: (_rule: any, value: any, callback: any) => {
        const errorMessage = new FormTextFieldValidator({
          label: '密码',
          value: value,
        }).validate();

        errorMessage ? callback(new Error(errorMessage)) : callback();
      },
      trigger: 'change',
    },
  ],
});

const list = ref<any[]>([]);

for (let i = 0; i < 100; i++) {
  list.value.push({ id: i });
}

// function* filterItems(list: any[], predicate: (item: any) => boolean) {
//   for (const item of list) {
//     if (predicate(item)) {
//       yield item;
//     }
//   }
// }

async function login(
  username: string,
  password: string,
  rememberMe: boolean,
): Promise<void> {
  const res = await new AuthService().login(username, password);

  if (res?.accessToken) {
    RememberMeService.rememberMe = rememberMe;

    // Gets the server data to user instance.
    const user = User.fromJSON(res);

    const authenticationService = new AuthenticationService();

    // Saves the user data retrieved from server.
    authenticationService.saveUserInfo(user);

    // Saves current username for next logic form auto fill input.
    authenticationService.saveCurrentUsername();

    // Gets the server data to token instance.
    const token = await Token.fromServerJSON(res);

    // Saves the token data retrieved from server.
    TokenService.save(token);

    // Notifies change.
    authenticationStore.changeIsAuthenticated(
      AuthenticationService.isAuthenticated,
    );

    authenticationStore.changeCurrentUser(AuthenticationService.currentUser);

    authenticationStore.changeCurrentUsername(
      AuthenticationService.currentUsername,
    );

    const redirectTo = route.query.redirectTo?.toString() ?? '/home';

    // Once user logged in the login route will be replaced in the history stack.
    router.replace({ path: redirectTo });
  }
}

function submitForm(formEl: FormInstance | undefined): void {
  // if (!formEl) {
  //   return;
  // }

  formEl?.validate((valid) => {
    if (valid) {
      login(ruleForm.username!, ruleForm.password, ruleForm.rememberMe);
    }
  });
}
</script>

<template>
  <div class="container">
    <div class="form-container">
      <HelloWorld msg="Lala" />
      <h2 class="title">平台管理系统</h2>
      <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules">
        <el-form-item prop="username">
          <el-input v-model="ruleForm.username" placeholder="用户名" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="ruleForm.password"
            type="password"
            autocomplete="off"
            placeholder="密码"
          />
        </el-form-item>
        <el-form-item prop="rememberMe">
          <el-checkbox v-model="ruleForm.rememberMe">记住我</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            class="full-width"
            @click="submitForm(ruleFormRef)"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #fff;
}

.title {
  margin-top: 6px;
  align-self: center;
  margin-bottom: 10px;
}

.form-container {
  display: flex;
  flex-direction: column;
  width: 400px;
  background-color: #dcdcdc;
  margin-top: 180px;
  padding: 10px;
}

.form-button {
  width: 100%;
}
</style>
